/* Copyright (c) 2004-2022 peigen.info. All rights reserved. */

package info.peigen.hotpot.common.core.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.BitSet;

/**
 * <b>(BitmapUtil)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/8/24
 */
@SuppressWarnings("unused")
@Slf4j
public class BitmapUtil {
    private final BitSet bitSet;

    /**
     * @param length 位图长度，实际可操作下标为[0,length)
     */
    public BitmapUtil(int length) {
        bitSet = new BitSet(length);
    }

    /**
     * @param str 位图长度，实际可操作下标为[0,length)
     */
    public BitmapUtil(String str) {
        String[] strArray = StrUtil.split(str, 1);
        bitSet = new BitSet(str.length());
        for (int i = 0; i < strArray.length; i++) {
            String s = strArray[i];
            if (StrUtil.equals(s, "1")) {
                this.bitSet.set(i);
            }
        }
    }

    /**
     * 设置指定位的值
     *
     * @param index int
     */
    public void set(int index) {
        bitSet.set(index);
    }

    /**
     * 设置指定范围值
     *
     * @param indexFrom 定位起始位置
     * @param indexTo   定位结束位置
     */
    public void set(int indexFrom, int indexTo) {
        bitSet.set(indexFrom, indexTo);
    }

    /**
     * 获取指定位的值
     *
     * @param index int
     *
     * @return boolean
     */
    public boolean get(int index) {
        return bitSet.get(index);
    }

    /**
     * 获取指范围的值
     *
     * @param indexFrom 定位起始位置
     * @param indexTo   定位结束位置
     *
     * @return boolean
     */
    public boolean get(int indexFrom, int indexTo) {
        BitSet newBitSet = bitSet.get(indexFrom, indexTo);
        return bitSet.intersects(newBitSet);
    }

    /**
     * size
     *
     * @return int
     */
    public int size() {
        return bitSet.size();
    }
}